﻿using System;
using System.Reflection;
using System.Collections;

namespace YhmOA.Common
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
     public class CNNameAttribute : Attribute
    {
        private string _cnname;

        private PropertyInfo _propertyInfo;

        public string CNName
        {
            get { return _cnname; }
        }

        public CNNameAttribute(string cnname)
        {
            this._cnname = cnname;
        }

        public string PropertyInfoName
        {
            get { return _propertyInfo.Name; }
        }


        #region  对枚举描述属性的解释相关函数

        private static System.Collections.Hashtable cachedClass = new Hashtable();


        /// <summary>
        /// 得到实体类型中指定属性定义的中文文本
        /// </summary>
        /// <param name="classType">实体类型</param>
        /// <param name="proName">属性名称</param>
        /// <returns>指定属性定义的中文文本</returns>
        public static string GetPropertyText(Type classType, string proName)
        {
            CNNameAttribute[] cnnames = GetPropertyTexts(classType);
            foreach (CNNameAttribute c in cnnames)
            {
                if (c.PropertyInfoName == proName) return c.CNName;
            }
            return string.Empty;
        }

        /// <summary>
        /// 得到实体类型中属性定义的中文文本
        /// </summary>
        /// <param name="classType">实体类型</param>
        /// <returns>所有属性定义的中文文本</returns>
        public static CNNameAttribute[] GetPropertyTexts(Type classType)
        {
            CNNameAttribute[] cnnames = null;
            //缓存中没有找到，通过反射获得属性的描述信息
            if (cachedClass.Contains(classType.FullName) == false)
            {
                PropertyInfo[] infos = classType.GetProperties();
                ArrayList piAL = new ArrayList();
                foreach (PropertyInfo info in infos)
                {
                    object[] cnnameArr = info.GetCustomAttributes(typeof(CNNameAttribute), false);
                    if (cnnameArr.Length != 1) continue;
                    ((CNNameAttribute)cnnameArr[0])._propertyInfo = info;
                    piAL.Add(cnnameArr[0]);
                }

                cachedClass.Add(classType.FullName, (CNNameAttribute[])piAL.ToArray(typeof(CNNameAttribute)));
            }
            cnnames = (CNNameAttribute[])cachedClass[classType.FullName];
            if (cnnames.Length <= 0)
                Log.Error(String.Format("[{0}]未定义属性CNNameAttribute", classType.Name), null);

            return cnnames;
        }
        #endregion
    }
}
